#!/bin/env python3

# update issue status

import os
import sys
import requests
import argparse

par = argparse.ArgumentParser()
par.add_argument("-url", "--issue_url", default=None, nargs="+",
        help="issue url", required=True)
par.add_argument("-t", "--token", default=None,
        help="gitee api token", required=True)
par.add_argument("-s", "--status", default=None,
        help="change issue status", required=True)
args = par.parse_args()

def process_data():
    # process issue url data
    msg = []
    for i in range(len(args.issue_url)):
        repo_name = args.issue_url[i].split('/')[3]
        pkg = args.issue_url[i].split('/')[4]
        issue = args.issue_url[i].split('/')[6]
        tmp = {'repo_name': repo_name, 'pkg': pkg, 'issue': issue}
        msg.append(tmp)
    return msg

def update_issue(issue_msg):
    # update issue status
    error_list = []
    for tmp in issue_msg:
        api_url = "https://gitee.com/api/v5/repos/%s/issues/%s" % (tmp['repo_name'], tmp['issue'])
        msg = {'access_token': args.token, 'repo': tmp['pkg'], 'state': args.status}
        try:
            rep = requests.patch(url = api_url, data = msg)
            # if the status is not 200, an exception is thrown.
            rep.raise_for_status()
            print("INFO: update %s %s to %s succeed." % (tmp['pkg'], tmp['issue'], args.status))
        except:
            error_list.append(tmp)
            print("ERROR:%s %s %s  Failed_reason:%s" % (tmp['repo_name'], tmp['pkg'], tmp['issue'], rep.json()['message']))
    if error_list:
        print("##########Failed update issue state##########")
        for err in error_list:
            print(err)
        sys.exit(1)

msg = process_data()
update_issue(msg)
